//
//  WBStatusPictureView.swift
//  weibo
//
//  Created by wenquan wang on 1/4/17.
//  Copyright © 2017 wenquan wang. All rights reserved.
//

import UIKit

class WBStatusPictureView: UIView {
    var viewModel: WBStatusViewModel? {
        didSet{
            calcViewSize()
            urls = viewModel?.picURLs
        }
    }
    private func calcViewSize(){
        //width
        //single image
        if viewModel?.picURLs?.count == 1 {
            let viewSize = viewModel?.pictureViewSize ?? CGSize()
            let v = subviews[0]
            v.frame = CGRect(x: 0,
                             y: WBStatusPictureViewOutterMargin,
                             width: viewSize.width,
                             height: viewSize.height - WBStatusPictureViewOutterMargin)
        }
        else{
        //more than two imags
            let v = subviews[0]
            v.frame = CGRect(x: 0,
                             y: WBStatusPictureViewOutterMargin,
                             width: WBStatusPictureItemWidth,
                             height: WBStatusPictureItemWidth)
        }
        //height
        heightCons.constant = viewModel?.pictureViewSize.height ?? 0
    }
    private var urls: [WBStatusPicture]? {
        didSet {
            for v in subviews {
                v.isHidden = true
            }
            var index = 0
            for url in urls ?? []{
                let iv = subviews[index] as! UIImageView
                
                // pics == 4
                if index == 1 && urls?.count == 4{
                    index += 1
                }
                iv.cz_setImage(urlString: url.thumbnail_pic, placeholderImage: nil)
                iv.isHidden = false
                
                index += 1
            }
        }
    }
    //
    @IBOutlet weak var heightCons: NSLayoutConstraint!
    
    override func awakeFromNib() {
        setupUI()
    }
}

extension WBStatusPictureView{
    func setupUI(){
        backgroundColor = superview?.backgroundColor
        clipsToBounds = true
        
        let count = 9
        let rect = CGRect(x: 0, y: WBStatusPictureViewOutterMargin, width: WBStatusPictureItemWidth, height: WBStatusPictureItemWidth)
        for i in 0..<count{
            let iv = UIImageView()
            iv.contentMode = .scaleAspectFit
            iv.clipsToBounds = true
            
            iv.frame = rect
            //row -> y
            let row = CGFloat(i / count)
            //col -> x
            let col = CGFloat(i % count)
            let xOffset = col * (WBStatusPictureItemWidth + WBStatusPictureViewInnerMargin)
            let yOffset = row * (WBStatusPictureItemWidth + WBStatusPictureViewInnerMargin)
            iv.frame = rect.offsetBy(dx: xOffset, dy: yOffset)
            addSubview(iv)
        }
    }
}
